package com.frame.work.common.util;

import org.apache.commons.lang3.StringUtils;

import java.io.*;

//16进制转换
public class Util {
    static String intToHex(int data) {
        String lsData = Integer.toHexString(data);
        if (lsData.length() < 2) {
            return '0' + lsData;
        } else {
            return lsData;
        }
    }

    public static String calculateHexChecksum(String hexData) {
        int sum = calculateChecksum(hexData);
        //%02x x表示以十六进制形式输出
        //02 表示不足两位,，前面补0输出，如果超过两位，则以实际输出,
        return String.format("%02X", sum);
    }

    private static int calculateChecksum(String hexData) {
        int sum = 0;
        for (int i = 0; i < hexData.length(); i += 2) {
            String bytes = StringUtils.substring(hexData, i, i + 2);
            sum += Integer.parseInt(bytes, 16);
        }
        sum = sum & 0xff;
        return sum;
    }

    //读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //4位数高地位转换
    public static String twoReplace(String data) {
        return StringUtils.substring(data, 2, 4) + StringUtils.substring(data, 0, 2);
    }

    public static String fourReplace(String data) {
        return StringUtils.substring(data, 2, 4) + StringUtils.substring(data, 0, 2);
    }
    /**
     * 得到十六进制数的静态方法
     *
     * @param decimalNumber 十进制数
     * @return 四位十六进制数字符串
     */
    public static String getHexString(int decimalNumber) {
        //将十进制数转为十六进制数
        String hex = Integer.toHexString(decimalNumber);
        //转为大写
        hex = hex.toUpperCase();
        //加长到四位字符，用0补齐
        while (hex.length() < 4) {
            hex = "0" + hex;
        }
        return hex;

    }

}
